import Button from "@/component/Button";
import { useState } from "react";
import { ApiHttp } from "../../network/ApiHttp";
import { GlobalStore } from "../../store/GlobalStore";
import styles from './index.module.scss';
import { log_error } from "./log_error";
import { mix } from './mix';
import { Space } from "./Space";
import { Input } from "@/component/Input";
export function VisitorRow() {
  const [submitting, setSubmitting] = useState(false);
  const [{ username: _username }, dispatch] = GlobalStore.useStore();
  const [username, setUsername] = useState(_username);
  const [password, setPassword] = useState("");

  const onClickLogin = () => {
    if (submitting) return;
    setSubmitting(true);
    ApiHttp.post<any, any>(`user/login`, void 0, {
      username: username,
      password: mix(username, password)
    })
      .then(r => dispatch({ type: 'login', payload: r.data }))
      .catch(ApiHttp.ignoreAbort)
      .catch(log_error)
      .finally(() => setSubmitting(false));
  };

  const onClickRegister = () => {
    if (submitting) return;
    setSubmitting(true);
    ApiHttp.post<any, any>(`user/register`, void 0, {
      username: username,
      password: mix(username, password)
    })
      .then(r => dispatch({ type: 'login', payload: r.data }))
      .catch(ApiHttp.ignoreAbort)
      .catch(log_error)
      .finally(() => setSubmitting(false));
  };
  return (
    <div className={styles.visitor_row}>
      <Space vertical >
        <Space align='center'>
          账号
          <Input
            placeholder="账号"
            autoComplete="username"
            value={username}
            disabled={submitting}
            onChange={e => setUsername(e.target.value)} />
        </Space>
        <Space align='center'>
          
          密码
          <Input
            type="password"
            placeholder="密码"
            autoComplete="current-password"
            value={password}
            disabled={submitting}
            onChange={e => setPassword(e.target.value)} />
        </Space>
        <Space horizontal>
          <Button size='s' name="login" onClick={onClickLogin}
            disabled={submitting || !username || !password}>登录</Button>
          <Button size='s' name="register" onClick={onClickRegister}
            disabled={submitting || !username || !password}>注册</Button>
        </Space>
      </Space>
    </div>
  );
}

